<template>
    <el-dialog :visible.sync="visible" :title="dataForm.jobId ? '编辑' : '新增'" append-to-body>
        <el-form ref="dataForm" :model="dataForm" :rules="ruleValidate" label-width="300px">
            <el-row>
                <el-col :span="24">
                    <el-form-item label="注册号" prop="studentNo">
                        <el-input @input="selectStudent" v-model="dataForm.studentNo" placeholder="输入注册号"
                            clearable></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="24">
                    <el-form-item label="学生姓名" prop="studentName">
                        <el-input v-model="dataForm.studentName" disabled clearable></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="24">
                    <el-form-item label="学年" prop="schoolDateId">
                        <el-select @change="getScoreList" style="width: 100%;" v-model="dataForm.schoolDateId"
                            placeholder="请选择学年">
                            <el-option v-for="item in schooleDateList" :key="item.id" :label="item.namezh_CN" :value="item.id">
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col v-for="item in evaluateList" :key="item.id" :span="24">
                    <el-form-item :label="item.quotaDescription">
                        <el-input-number style="width:100%" v-model="dataForm[item.quotaId]" :precision="2" :min="-99.99"
                            :step="0.1" :controls="false" :max="item.maxScore"
                            :placeholder="`输入${item.quotaDescription}`"></el-input-number>
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
        <div slot="footer">
            <!-- <el-button type="text" @click="handleCancel">取消</el-button> -->
            <el-button type="primary" :loading="showLoading" @click="submit">提交评价</el-button>
        </div>
    </el-dialog>
</template>
<script>
import {
    queryStudent,
} from "@/api/information/studentInfor";
import { schooledateList } from "@/api/information/schoolCalendar"
import {
    scoreStatisticsList,
    getInfoByStudentIdAndSchoolDateId
} from "@/api/assessmentCenter/evaluationIndex";
import {
    evaluateList,
    postEvaluateInfo,
    putEvaluateInfo

} from "@/api/assessmentCenter/evaluationIndex";

export default {
    data() {
        return {
            visible: false,
            showLoading: false,
            dataForm: {
                studentNo: null,
                studentName: '',
                schoolDateId: null
            },
            evaluateList: [],
            schooleDateList: [],
            ruleValidate: {
                studentNo: [
                    { required: true, message: '请输入注册号', trigger: 'blur' }
                ],
                schoolDateId: [
                    { required: true, message: '请输入学年信息', trigger: 'blur' }
                ],

            }
        }
    },
    dicts: [
        "basic_term_type"
    ],
    methods: {
        init(data) {
            // add or update
            this.visible = true;
            this.$nextTick(() => {
                this.$refs['dataForm']?.resetFields();
            });

            this.dataForm = {
                studentNo: null,
                studentName: '',
                schoolDateId: null
            }
            if (data) {
                this.$nextTick(() => {
                    this.dataForm = { ...data };
                });
            } else {
                this.$nextTick(() => {
                    this.$refs['dataForm'].resetFields();
                });
            }
            this.getEvaluateListAndSchoolYear()
        },

        handleCancel() {
            this.visible = false;
            this.disablePassword = true;
            this.showLoading = false;
        },
        handleSubmit() { // 表单提交
            let param = { ...this.dataForm }
            this.$refs['dataForm'].validate(async (valid) => {
                if (valid) {
                    if (!this.dataForm.studentName) {
                        this.$message.error("请输入正确的学号")
                        return;
                    }
                    this.showLoading = true;
                    let data = {}
                    if (this.dataForm.id) {
                        data = await editData(param)
                    } else {
                        data = await addData(param)
                    }
                    if (data && data.code === 200) {
                        this.$modal.msgSuccess("操作成功");
                        this.handleCancel();
                        this.$emit('refreshDataList')

                    } else {
                        this.$message.error(data.msg);
                        this.showLoading = false;
                    }
                }
            })
        },
        // 查询学生信息
        async selectStudent() {
            const { data } = await queryStudent({
                registerOrSno: this.dataForm.studentNo
            })
            this.dataForm.schoolDateId = null;
            if (data) {
                this.dataForm.studentName = data.name
                this.dataForm.studentId = data.id
                // 有学年的情况下查询明细
                if(this.dataForm.schoolDateId) {
                    this.queryScoreStatisticsRowData();
                }
            } else {
                this.dataForm.studentName = ''
                this.dataForm.studentId = null
            }
        },
        queryScoreStatisticsRowData() {
            getInfoByStudentIdAndSchoolDateId({
                studentId: this.dataForm.studentId,
                schoolDateId: this.dataForm.schoolDateId
            }).then((response) => {
                response.data?.evaluateScoreList?.map(res=>{
                    this.dataForm[res.quotaId] = res.realScore
                })
                if (response.data) {
                    this.dataForm.evaluateId = response.data.evaluateId
                }
            })
        },
        // 提交评价
        async submit() {
            let evaluateScoreList = [], totalScore = 0;
            for (let k in this.dataForm) {
                if (k != "schoolDateId" && k != "studentName" && k != "studentNo" && k != "studentId" && k != "evaluateId") {
                    if (this.dataForm[k] != undefined && k) {
                        evaluateScoreList.push({
                            realScore: this.dataForm[k],
                            quotaId: k
                        })
                        totalScore += this.dataForm[k]
                    }
                }
            }
            let data = null
            if (this.dataForm.evaluateId) {
                data = await putEvaluateInfo({
                    evaluateScoreList,
                    totalScore,
                    schoolDateId: this.dataForm.schoolDateId,
                    registerCode: this.dataForm.studentNo,
                    studentId: this.dataForm.studentId,
                    evaluateId: this.dataForm.evaluateId
                })
            } else {
                data = await postEvaluateInfo({
                    evaluateScoreList,
                    totalScore,
                    schoolDateId: this.dataForm.schoolDateId,
                    registerCode: this.dataForm.studentNo,
                    studentId: this.dataForm.studentId,
                })
            }

            if (data && data.code === 200) {
                this.$modal.msgSuccess("操作成功");
                this.handleCancel();
                this.$emit('refreshDataList')

            } else {
                this.$message.error(data.msg);
                this.showLoading = false;
            }
        },
        // 获取 该学生在本学期的记录
        async getScoreList(e) {
            if (!this.dataForm.studentId) {
                return
            } else {
                // const { rows } = await scoreStatisticsList({
                //     studentId: this.dataForm.studentId,
                //     schoolDateld: e
                // })
                this.queryScoreStatisticsRowData();
            }
        },
        // 获取指标项及学年列表
        async getEvaluateListAndSchoolYear() {
            const { rows } = await evaluateList({useStatus:0,pageNum:1,pageSize:9999})
            this.evaluateList = rows;
            rows.forEach(element => {
                this.dataForm[element.quotaId] = undefined
            });
            schooledateList().then(res => {
                this.schooleDateList = res.rows.map((item) => {
                    const termItem = this.dict.type.basic_term_type.find((dictItem) => { return dictItem.value === item.termName})
                    item.namezh_CN = termItem ? item.name+ ' ' + termItem.label : ''
                    return item
                })
            })
        }
    },
    async mounted() {
    },
}
</script>
  